import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const isAuthenticated = ref(false)

  // 模拟登录（实际应对接后端接口校验）
  const login = (username, password) => {
    // 简单示例：只要输入不为空就视为登录成功
    if (username.trim() && password.trim()) {
      user.value = { username }
      isAuthenticated.value = true
      localStorage.setItem('user', JSON.stringify(user.value))
      return true
    }
    return false
  }

  // 登出
  const logout = () => {
    user.value = null
    isAuthenticated.value = false
    localStorage.removeItem('user')
  }

  // 初始化时尝试从本地存储恢复登录状态
  const initUser = () => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      user.value = JSON.parse(storedUser)
      isAuthenticated.value = true
    }
  }
  initUser()

  return { user, isAuthenticated, login, logout }
})